# -*- coding: utf-8 -*-
#
#
##

##
#=== Rakuten item search API wrapper
#   http://webservice.rakuten.co.jp/api/itemsearch/
#
class ItemSearch < RakutenApiBase
	#
	#=== search method 
	#
	def search(keyword)
		prm = {}
		prm['keyword'] = keyword
		prm['developerId'] = @developerId
		prm['affiliateId'] = @affiliateId

		iss = @@rakuten_settings['itemsearch']
		prm['operation'] = iss['operation']
		prm['version'] = iss['version']
		prm['imageFlag'] = iss['imageFlag']
		prm['sort'] = iss['sort']
		prm['availability'] = iss['availability']
		prm['purchaseType'] = iss['purchaseType']

		xmltext = getWebContents(@restUrl,prm)
		unless xmltext or xmltext != ''
			return false
		end
		
		xobj = parseXMLObject(xmltext)
		unless xobj
			return false
		end
		item = REXML::XPath.first( xobj, 'Body/itemSearch:ItemSearch/Items/Item')
		if item
			ret = {}
			ret[:itemName] = item.elements['itemName'].text
			ret[:itemCode] = item.elements['itemCode'].text
			ret[:webUrl] = item.elements['affiliateUrl'].text
			ret[:imageUrl] = item.elements['mediumImageUrl'].text
			ret[:genreId] = item.elements['genreId'].text.to_i
			ret[:barcode] = keyword
			return ret
		else
			return false
		end
	end

	#
	#=== search method 
	#
	def getItemInfo(keyword)
		begin
			irt = search(keyword)

			grt = GenreSearch.new.searchRootGenre(irt[:genreId])
			irt[:rootgenreId] = grt[:genreId]
			gl = ItemSearch.getGenreList()
			irt[:potid] = gl[grt[:genreId]]['potid']
			irt[:special] = gl[grt[:genreId]]['special']
			return irt
		rescue 
			return false
		end	
	end


			
			
	#
	#=== test method
	#
	def self.test()
        u = User.find(1)
        st = u.getPots()
#        pp st
#        u = User.find(2)
        st = u.getPots()
#        pp st


		is = ItemSearch.new
		irt = is.search('4901777215672')
		pp irt
		irt = is.search('4946842501915')
		pp irt
		irt = is.search('4987035089315')
		pp irt
		irt = is.search('4981254548608')
		pp irt
		irt = is.search('4901872507924')
		pp irt
#  4902471033791
#  49770780
# 4946842501908
		
#		gid = irt[:genreId]
#		gs = GenreSearch.new
#		grt = gs.searchRootGenre(gid)
#		pp grt
		
		
 		#pp is.search('4946842501915')
	end

	def self.testbarcode()
		url = "#{BKH_API_URL}barcode"
		userid=1
		barcodes = [
		"4901777215672",
		"4946842501915",
		"4987035089315",
		"4981254548608",
		"4901872507924",
		"4946842501915",
		"4902471033791",
		"49770780",
		"4946842501908",
		"4902204437285",
		"4964888430341",
		"4901919006670",
		"4902820128000",
		"4902179013699",
		"4901777216716",
		"4902501221310",
		"4543112647504",
		"4548835892286",
		"4548804873438",
		"4936790502256",
		"4901777196094"
		]
		barcodes.each(){|barcode|
			param = {'userid' => userid, 'barcode'=>barcode}
			getWebContents(url,param)
		}

	end

end


